package com.mua.test.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mua.test.user.entity.User;
import com.mua.test.user.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author JiangLan
 * @since 2024/4/19 15:28
 */
@Component
public class SecurityUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    /*@Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        User u = userMapper.selectOne(queryWrapper);
        if(ObjectUtils.isEmpty(u)){
            u = new User();
            u.setUsername(user.getUsername());
            u.setPassword(passwordEncoder.encode(user.getPassword()));
            userMapper.insert(u);
        }
        else {
            // 已存在生效用户
            if(u.getEnabled()){
                throw new UserExistsException(user.getUsername());
            }
            // 失效改生效
            else {
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper
                        .set("enabled", true)
                        .set("password", passwordEncoder.encode(user.getPassword()))
                        .eq("username", user.getUsername());
                userMapper.update(updateWrapper);
            }
        }
    }

    @Override
    public void updateUser(UserDetails user) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("password", user.getPassword())
                .eq("username", user.getUsername());
        userMapper.update(updateWrapper);
    }

    @Override
    public void deleteUser(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        userMapper.delete(queryWrapper);
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", SecurityContextHolder.getContext().getAuthentication().getName());
        User u = userMapper.selectOne(queryWrapper);
        if(u.getPassword().equals(oldPassword)){
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .set("password", newPassword)
                    .eq("username", u.getUsername());
            userMapper.update(updateWrapper);
        }
        else {
            throw new PasswordException("原密码错误，修改失败！");
        }
    }

    @Override
    public boolean userExists(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.exists(queryWrapper);
    }*/

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isBlank(username)){
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username).eq("enabled", true);
        User user = userMapper.selectOne(queryWrapper);
        if(ObjectUtils.isNull(user)){
            throw new UsernameNotFoundException(username);
        }
        /*// todo 这里明天改成数据库的设计，暂时测试用硬编码
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(() -> "USER_LIST");
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                true,
                true,
                true,
                true,
                authorities
        );*/
        // 基于角色控制权限
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .disabled(!user.getEnabled())
                .credentialsExpired(false)
                .accountLocked(false)
                .roles("ADMIN")
                .authorities("USER_ADD", "USER_DELETE")
                .build();
        return userDetails;
    }
}
